package com.assets.Fragment;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;

import com.assets.Adapter.Item_receive_Adapter;
import com.assets.Adapter.ReceiveData;
import com.assets.Check.Check;
import com.assets.Ip_set.Url;
import com.assets.R;
import com.assets.Receive.Receive_add;
import com.assets.Receive.Receive_issued;
import com.assets.bean.receives_bean;
import com.assets.menu.SlideSideMenuExampleActivity;
import com.assets.newNHF.util.LogUtils;
import com.assets.room.database.MyDataBase;
import com.assets.room.entity.Receives;
import com.assets.room.entity.User;
import com.assets.util.MyOkHttp;
import com.assets.util.Since_case;
import com.assets.util.TrustAllCerts;
import com.demo.WaveSwipeRefreshLayout;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.lemonade.widgets.slidesidemenu.SlideSideMenuTransitionLayout;

import org.apache.http.conn.ssl.AllowAllHostnameVerifier;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

/**
 * 这个是领用页面
 */

public class Fragment3 extends Fragment {

    private static final String TAG = "领用页面";
    private SlideSideMenuExampleActivity mainActivity;
    private ListView lv_list;
    private WaveSwipeRefreshLayout mWaveSwipeRefreshLayout;
    private ImageView screen;
    private String url = "http://" + Url.IP + "/api/receivesQuery";
    private static int imageResourceIndex = 0;
    private List<ReceiveData> list = new ArrayList<ReceiveData>();//全部
    private List<receives_bean> userList;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment_second3, null);
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        mainActivity = (SlideSideMenuExampleActivity) getActivity();
        SharedPreferences mm = getActivity().getSharedPreferences("mm", Context.MODE_PRIVATE);//1.通过上下文得到
        LogUtils.d(Url.IP);
        init();
    }

    private void init() {

        TextView title = mainActivity.findViewById(R.id.title_text);
        title.setText("领用");
        screen = (ImageView) mainActivity.findViewById(R.id.screen);
        lv_list = (ListView) getActivity().findViewById(R.id.lv_Receive);
        ImageView add = (ImageView) getActivity().findViewById(R.id.add);
        add.setOnClickListener(v -> {
            Intent intent = new Intent(mainActivity, Receive_add.class);
            startActivity(intent);
        });
        lv_list.setOnItemClickListener((adapterView, view, i, l) -> {


//            for (int i1 = 0; i1 < list.size(); i1++) {
//
//                if ("3".equals(list.get(i1).getStatus())) {
//                    return;
//                }
//
//            }
//            for (int j = 0; j < userList.size(); i++) {
//
//
//
//            }
            Intent intent = new Intent(mainActivity, Receive_issued.class);
            intent.putExtra("coding_name", String.valueOf(list.get(i).getNo()));
            intent.putExtra("status", String.valueOf(list.get(i).getStatus()));
            startActivity(intent);
            /*if (String.valueOf(list.get(i).get("scope")).equals("待发放") || String.valueOf(list.get(i).get("scope")).equals("部分发放")) {
                Intent intent = new Intent(mainActivity, Grant_rfid.class);
                intent.putExtra("coding_name", String.valueOf(list.get(i).get("odd")));
                intent.putExtra("status", String.valueOf(list.get(i).get("scope")));
                startActivity(intent);
            } else {
                Intent intent = new Intent(mainActivity, Receive_issued.class);
                intent.putExtra("coding_name", String.valueOf(list.get(i).get("odd")));
                intent.putExtra("status", String.valueOf(list.get(i).get("scope")));
                startActivity(intent);
            }*/
        });
        ImageView imageView = (ImageView) getActivity().findViewById(R.id.opmenu);
        imageView.setOnClickListener(v -> {
            SlideSideMenuTransitionLayout mSlideSideMenu = (SlideSideMenuTransitionLayout) getActivity().findViewById(R.id.slide_side_menu);
            mSlideSideMenu.toggle();
        });
        mWaveSwipeRefreshLayout = (WaveSwipeRefreshLayout) getActivity().findViewById(R.id.main_swipe);
        mWaveSwipeRefreshLayout.setColorSchemeColors(Color.WHITE, Color.WHITE);//设置水滴中旋转动画的颜色，参数1:水滴落下过程中的颜色，参数2:水滴已经落下后的颜色
        mWaveSwipeRefreshLayout.setWaveColor(0xFF3794fc);//设置水滴样色
        //mWaveSwipeRefreshLayout.setMaxDropHeight(1500);//设置最大下拉高度
        mWaveSwipeRefreshLayout.setOnRefreshListener(new WaveSwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                new Handler().postDelayed(new Runnable() {//模拟3秒的加载过程
                    @Override
                    public void run() {
                        load();
                        //接下来可以刷新ListView
                    }
                }, 1200);
            }
        });
    }

    @Override
    public void onStart() {
        Timer timer = new Timer();//实例化Timer类
        timer.schedule(new TimerTask() {
            public void run() {
                LogUtils.d("3");
                load();
                this.cancel();
            }
        }, 300);//五百毫秒
        super.onStart();
    }

    private void load() {
        new Thread() {
            @Override
            public void run() {
//

                List<Map<String, Object>> mapList = new ArrayList<>();
                //通过userId查出User表里面对应的数据
                User user = MyDataBase.init(mainActivity).userDao().getUserById(Since_case.getInstance().getUserId());

                Log.d(TAG, "user: " + user);
                if (user != null) {

                    List<Receives> allReceives = MyDataBase.init(mainActivity).receivesDao().getAllReceives();

                    Log.d(TAG, "allReceives: " + allReceives);
                    for (int i = 0; i < allReceives.size(); i++) {
                        Map<String, Object> map = new HashMap<>();
                        map.put("receivesDept", allReceives.get(i).getReceivesDept());
                        map.put("receivesId", allReceives.get(i).getReceivesId());
                        map.put("receivesUser", allReceives.get(i).getReceivesUser());
                        map.put("reapplyDate", allReceives.get(i).getReapplyDate());
                        map.put("createUser", allReceives.get(i).getCreateuser());
                        map.put("sum", MyDataBase.init(mainActivity).receivesReapplyDao().getSumById(allReceives.get(i).getReceivesId()));
                        map.put("place", allReceives.get(i).getPlace());
                        map.put("receivesDate", allReceives.get(i).getReceivesDate());
                        map.put("status", allReceives.get(i).getStatus());
//                        go(map);
//                        Log.d(TAG, "allReceives: " + map.get("receivesId").toString());
                        mapList.add(map);
//                        Log.d(TAG, "run: " + mapList.get(i));
                    }
                    showResponse(new Gson().toJson(mapList));
//                    allReceives.stream().map(bean -> {
//
//                        map.put("receivesDept", bean.getReceivesDept());
//                        map.put("receivesId", bean.getReceivesId());
//                        map.put("receivesUser", bean.getReceivesUser());
//                        map.put("reapplyDate", bean.getReapplyDate());
//                        map.put("createUser", bean.getCreateuser());
//                        map.put("sum", MyDataBase.init(mainActivity).receivesReapplyDao().getSumById(bean.getReceivesId()));
//                        map.put("place", bean.getPlace());
//                        map.put("receivesDate", bean.getReceivesDate());
//                        map.put("status", bean.getStatus());
//                        mapList.add(map);
//                        return mapList;
//                    }).collect(Collectors.toList());

//
                }
//
//                mapList.addAll(mapList);

//                String submitData = MyOkHttp.getInstance().getGson().toJson(mapList);
//
//                Log.d(TAG, "组装的数据: " + submitData);
//                showResponse(submitData);


//                try {
//                    OkHttpClient client = new OkHttpClient
//                            .Builder()
//                            .hostnameVerifier(new AllowAllHostnameVerifier())
//                            .sslSocketFactory(TrustAllCerts.createSSLSocketFactory(), TrustAllCerts.getX509TrustManager())
//                            .connectTimeout(10, TimeUnit.SECONDS)//连接超时
//                            .readTimeout(500, TimeUnit.SECONDS)
//                            .build();
//                    RequestBody requestBody = new FormBody.Builder()
//                            .add("userId", Since_case.getInstance().getUserId())
//                            .build();
//                    Request request = new Request.Builder()
//                            .url(url)
//                            .post(requestBody).build();
//                    Response response = client.newCall(request).execute();
//                    String responseData = response.body().string();
//                    Log.d(TAG, "responseData: " + responseData);
//                    showResponse(responseData);
//                } catch (IOException e) {
//                    e.printStackTrace();
//                }
            }
        }.start();
    }

    private void showResponse(final String responseData) {
        LogUtils.d(responseData);
        mainActivity.runOnUiThread(() -> {

            try {
                list.clear();
                if (responseData.equals("[]")) {
                    Toast.makeText(mainActivity, "无领用单", Toast.LENGTH_SHORT).show();
                    return;
                }
                mWaveSwipeRefreshLayout.setRefreshing(false);//停止加载动画
                Gson gson = new Gson();
                userList = gson.fromJson(responseData, new TypeToken<List<receives_bean>>() {
                }.getType());
                for (int i = 0; i < userList.size(); i++) {
                    String zt = "";
                    String numName = "";
                    if (userList.get(i).getStatus().equals("1")) {
                        zt = "申请中";
                    }
                    if (userList.get(i).getStatus().equals("2")) {
                        zt = "待发放";
                    }
                    if (userList.get(i).getStatus().equals("3")) {
                        zt = "已全部发放";
                    }
                    if (userList.get(i).getStatus().equals("0")) {
                        zt = "驳回";
                    }
                    if (userList.get(i).getStatus().equals("4")) {
                        zt = "部分发放";
                        numName = "待发数量";
                    }
                    if (userList.get(i).getStatus().equals("5")) {
                        zt = "已发放，复审通过";
                    }
                    String receivesDate = "", reapplyDate = "";

                    if (userList.get(i).getReceivesDate().equals("")) {
                        receivesDate = userList.get(i).getReceivesDate();
                    } else {
                        receivesDate = userList.get(i).getReceivesDate().substring(0, 10);
                    }
                    if (userList.get(i).getReapplyDate().equals("")) {
                        reapplyDate = userList.get(i).getReapplyDate();
                    } else {
                        reapplyDate = userList.get(i).getReapplyDate().substring(0, 10);
                    }
                    ReceiveData data = new ReceiveData(userList.get(i).getReceivesId(), userList.get(i).getReceivesDept(), zt, MyDataBase.init(mainActivity).userDao().getUserById(userList.get(i).getCreateUser()) == null ? "":MyDataBase.init(mainActivity).userDao().getUserById(userList.get(i).getCreateUser()).getName(), MyDataBase.init(mainActivity).userDao().getUserById(userList.get(i).getReceivesUser()) ==null ? "" : MyDataBase.init(mainActivity).userDao().getUserById(userList.get(i).getReceivesUser()).getName(),  MyDataBase.init(mainActivity).placeDao().getNameById(userList.get(i).getPlace()) == null ? "" :  MyDataBase.init(mainActivity).placeDao().getNameById(userList.get(i).getPlace()), reapplyDate, receivesDate);
                    data.setNumName(numName);
                    list.add(data);
                }
                Collections.reverse(list);
                //适配器，刚刚重写的！
                Item_receive_Adapter re_ad = new Item_receive_Adapter(mainActivity, list);
                lv_list.setAdapter(re_ad);
            } catch (Exception e) {
                e.printStackTrace();
            }
        });
    }

//    void go(Map<String, Object> map) {
//
//        map.put("receivesDept", 1);
//        map.put("receivesId", 1);
//        map.put("receivesUser", allReceives.get(i).getReceivesUser());
//        map.put("reapplyDate", allReceives.get(i).getReapplyDate());
//        map.put("createUser", allReceives.get(i).getCreateuser());
//        map.put("sum", MyDataBase.init(mainActivity).receivesReapplyDao().getSumById(allReceives.get(i).getReceivesId()));
//        map.put("place", allReceives.get(i).getPlace());
//        map.put("receivesDate", allReceives.get(i).getReceivesDate());
//        map.put("status", allReceives.get(i).getStatus());
//    }
}
